package com.shsappdev.shsfalconbeta;

import java.util.Collections;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;

import com.shsappdev.shsfalconbeta.article.Article;
import com.shsappdev.shsfalconbeta.article.ArticleInflater;
import com.shsappdev.shsfalconbeta.article.ArticleManager;
import com.shsappdev.shsfalconbeta.webserver.WebServer;

public class SearchFragment  extends BaseFragment {

	public SearchFragment() {
		super();
		displayLoadMore = false;
	}
	
	public String getType() {
		return "search";
	}

	public String getName() {
		return "search";
	}
	
	@Override
	public boolean pullCache() {
		return false;
	}

	public int getImage() {
		return R.drawable.ic_action_search;
	}

	@Override
	public void pushForMore(boolean append) {
		isFetching = true;
		Log.d("SHS Falcon: Fragment", "Pulling nids...");
		(new Thread() {
			public void run() {
				int[] newNids = WebServer.getStoryNidsWithTerms(((SearchActivity)(getActivity())).query);
				((SearchActivity)getActivity()).setResultsText(0);
				if(newNids != null) {
					nids = newNids;
					((SearchActivity)getActivity()).setResultsText(nids.length);
					notifyArticleChange();
					for(int i = 0; i < nids.length; i++) {
						ArticleManager.pullArticleWithNid(getActivity(), nids[i], getName());
					}
				}
			}
		}).start(); 
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		if(id == 0) {
			pushForMore(true);
		} else {
			((SearchActivity)getActivity()).viewArticle(ArticleManager.getArticleWithNid((int)id));
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	public void addArticle(final Article a) {
		handler.post(new Runnable() {
			public void run() {
				articles.add(a);
				Collections.sort(articles);
				notifyArticleChange();
			}
		});
	}
	
	public void refreshArticles() {
		for(int i = 0; i < nids.length; i++) {
			ArticleManager.pullArticleWithNid(getActivity(), nids[i], getName());
		}
	}

	@Override
	public View getInflater(LayoutInflater inflater, Article article) {
		View item = ArticleInflater.inflateRegularItem(inflater, article);
		return item;
	}

}